<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <a-row>
        <!-- <a-col :span="8" :offset="10">
          <a-input-search
            v-action:search
            style="max-width: 300px; min-width: 150px; float: right"
            v-model="queryParam.search"
            placeholder="请输入课程名字"
            @search="onSearch"
          />
        </a-col> -->
        <div class="row-item-tab clearfix">
          <a-range-picker @change="onSelectDate" />
          <a-button icon="download" @click="onExport">订单导出</a-button>
        </div>
      </a-row>
    </div>
    <s-table ref="table" rowKey="order_no" :loading="isLoading" :columns="columns" :data="loadData" :pageSize="15">
      <div slot="opening_time" slot-scope="text, item">
        <a-tooltip placement="right" arrow-point-at-center>
          <template slot="title">
            {{ text }}
          </template>
          <div class="opening_time">{{ text }}</div>
        </a-tooltip>
      </div>
      <div slot="course_detail" slot-scope="text, item">
        <a-tooltip placement="right" arrow-point-at-center>
          <template slot="title">
            {{ text }}
          </template>
          <div class="course_detail">{{ text }}</div>
        </a-tooltip>
      </div>
    </s-table>
    <AddForm ref="AddForm" @handleSubmit="handleRefresh" />
    <EditForm ref="EditForm" @handleSubmit="handleRefresh" />
  </a-card>
</template>

<script>
import * as Api from '@/api/course/index'
import { STable } from '@/components'
import AddForm from './modules/AddForm.vue'
import EditForm from './modules/EditForm.vue'
import ExcelJS from 'exceljs'
import * as FileSaver from 'file-saver'

export default {
  name: 'CourseOrder',
  components: {
    STable,
    AddForm,
    EditForm,
  },
  data() {
    return {
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '订单号',
          dataIndex: 'order_no',
          align: 'center',
        },
        {
          title: '微信交易号',
          dataIndex: 'transaction_id',
          align: 'center',
        },
        {
          title: '课程名称',
          dataIndex: 'course_name',
          align: 'center',
        },
        {
          title: '用户',
          dataIndex: 'user.nick_name',
          align: 'center',
        },
        {
          title: '价格',
          dataIndex: 'price',
          align: 'center',
        },
        {
          title: '购买时间',
          dataIndex: 'pay_time',
          align: 'center',
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (param) => {
        return Api.orderList({ ...param, ...this.queryParam }).then((response) => {
          console.log(response)
          return response.data
        })
      },
      // 选择的导出日期
      exportDate: [],
    }
  },
  created() {},
  methods: {
    /**
     * 新增记录
     */
    handleAdd() {
      this.$refs.AddForm.add()
    },

    /**
     * 编辑记录
     */
    handleEdit(item) {
      this.$refs.EditForm.edit(item)
    },

    /**
     * 删除记录
     */
    handleDelete(item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {},
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },

    /**
     * 检索查询
     */
    onSearch() {
      this.handleRefresh(true)
    },

    // 导出订单，默认导出当前页数据
    async onExport() {
      const workbook = new ExcelJS.Workbook()
      const sheet = workbook.addWorksheet('课程订单')
      sheet.columns = [
        { header: '订单号', key: 'order_no', width: 32 },
        { header: '微信交易号', key: 'transaction_id', width: 32 },
        { header: '课程名称', key: 'course_name', width: 12, outlineLevel: 1 },
       { header: '用户昵称', key: 'nick_name', width: 10, outlineLevel: 1 },
        { header: '用户姓名', key: 'real_name', width: 10, outlineLevel: 1 },
        { header: '价格', key: 'price', width: 10, outlineLevel: 1 },
        { header: '购买时间', key: 'pay_time', width: 22, outlineLevel: 1 },
      ]

      let fileName = `最近的课程购买记录.xlsx`
      let { data } = await this.loadData()
      // 有选择导出日期，则按导出日期查询后台
      if (this.hasSelectExportDate()) {
        const dateArr = this.exportDate
        fileName = `课程购买记录${dateArr[0]}~${dateArr[1]}`
        const result = await Api.orderListFilter({ dateArr })
        data = result.data
      }

      console.log(data)
      for (let i = 0, len = data.length; i < len; i++) {
        const item = data[i]

        sheet.addRow({
          order_no: item.order_no,
          transaction_id: item.transaction_id,
          course_name: item.course_name,
          price: item.price,
          nick_name: item.user.nick_name,
          real_name: item.user.real_name,
          pay_time: item.pay_time,
        })
      }

      const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
      workbook.xlsx
        .writeBuffer()
        .then((buffer) => {
          const blob = new Blob([buffer], { type: EXCEL_TYPE })
          FileSaver.saveAs(blob, fileName)
        })
        .catch((err) => {
          console.log(err)
        })
    },

    hasSelectExportDate() {
      if (this.exportDate?.[0]) {
        return true
      }

      return false
    },

    onSelectDate(date, dateString) {
      this.exportDate = dateString
    },
  },
}
</script>

<style lang="less" scoped>
.opening_time,
.course_detail {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
